package com.ljx.itbbs.server.user.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.ljx.itbbs.server.user.dao.MenuDao;
import com.ljx.itbbs.server.user.domain.entity.MenuEntity;
import com.ljx.itbbs.server.user.domain.vo.req.MenuSaveReq;
import com.ljx.itbbs.server.user.domain.vo.req.MenuUpdateReq;
import com.ljx.itbbs.server.user.domain.vo.resp.MenuTree;
import com.ljx.itbbs.server.user.domain.vo.resp.MenuResp;
import com.ljx.itbbs.server.user.service.MenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author: LiJunXi
 * @Description:
 * @Date: 2024-04-01  16:15
 */
@Service
public class MenuServiceImpl implements MenuService {

    @Autowired
    private MenuDao menuDao;

    @Override
    public List<MenuResp> getUserMenuList(Long userId) {
        return menuDao.getUserMenuList(userId);
    }

    @Override
    public List<MenuResp> getParentMenu() {
        return BeanUtil.copyToList(menuDao.getParentMenu(), MenuResp.class);
    }

    @Override
    public List<MenuTree> getMenuList() {
        List<MenuEntity> adminMenuList = menuDao.list();
        List<MenuTree> adminMenuTrees = new ArrayList<>();
        for(MenuEntity adminMenu: adminMenuList){
            MenuTree parTree = new MenuTree();
            List<MenuEntity> adminMenuChildTree = new ArrayList<>();
            // 找出父树
            if(adminMenu.getParentId().equals(0L)){
                // 找子树
                for(MenuEntity adminMenuitem: adminMenuList){
                    if (adminMenuitem.getParentId().equals(adminMenu.getId())){
                        adminMenuChildTree.add(adminMenuitem);
                    }
                }
                parTree.setTitle(adminMenu.getTitle());
                parTree.setId(adminMenu.getId());
                parTree.setHidden(adminMenu.getHidden());
                parTree.setCreateTime(adminMenu.getCreateTime());
                parTree.setIcon(adminMenu.getIcon());
                parTree.setStatus(adminMenu.getStatus());
                parTree.setMenuTrees(adminMenuChildTree);
                adminMenuTrees.add(parTree);
            }
        }
        return adminMenuTrees;
    }

    @Override
    public void updateMenu(MenuUpdateReq req) {
        menuDao.updateMenu(req);
    }

    @Override
    public void saveMenu(MenuSaveReq req) {
        MenuEntity menuEntity = BeanUtil.copyProperties(req, MenuEntity.class);
        menuDao.save(menuEntity);
    }

}
